package com.lecture.java8.multithreading;

import lombok.SneakyThrows;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author luyn
 * @version 1.0
 * @description 解决线程安全：使用lock锁
 * synchronized和lock锁的区别
 * 相同：两者都能解决线程安全问题
 * 不同：synchronized机制在执行完相应的同步代码以后，自动的释放同步监视器
 *      lock需要手动的启动同步（lock方法）同时结束同步也需要手动的实现（unlock方法）
 *
 * @date 2021/1/14 20:37
 */
public class LockTest {
    public static void main(String[] args) {
        WindowLock w = new WindowLock();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t1.start();
        t2.start();
        t3.start();
    }
}

class WindowLock implements Runnable {

    private int ticket = 100;

    private ReentrantLock lock = new ReentrantLock();

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            try {
                //调用lock方法加锁
                lock.lock();
                if (ticket > 0) {
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + "售票，票号为：" + ticket);
                    ticket --;
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //解锁方法
                lock.unlock();
            }
        }
    }
}